package com.hqbzl.chat.test;

import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.hqbzl.chat.message.RpcResponseMessage;
import com.hqbzl.chat.model.UserInfo;
import lombok.Data;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Type;
import java.util.Map;

@Slf4j
public class Example {

    @Data
    static class Person<T> {
        private String name;
        private T extend; // 嵌套对象类型
        private Class returnType;

    }

    @Data
    static class Teacher {
        private String addr;
        private Integer number;
    }

    public static <T> Person<T> parseJson(String data, Class<T> clazz) {
        try {
            return new Gson().fromJson(data, new TypeToken<Person<T>>() {
            }.getType());
        } catch (Throwable e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        final Teacher teacher = new Teacher();
        teacher.setAddr("beijing");
        teacher.setNumber(1357);

        final Person person = new Person();
        person.setName("lisi");
        person.setExtend(teacher);
        person.setReturnType(Teacher.class);

        final GsonBuilder gsonBuilder = new GsonBuilder()
                .registerTypeAdapter(Class.class, new TestJson.ClassCodec());
        final Gson gson = gsonBuilder.create();
        final String s = gson.toJson(person);
        System.out.println("s = " + s);
        Type jsonType = new TypeToken<Person<Teacher>>() {
        }.getType();
        final Person person1 = gson.fromJson(s, jsonType);
        final Teacher extend = (Teacher) person1.getExtend();
        System.out.println("extend.getClass() = " + extend.getClass());
    }

}

